package com.main.controller;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Iterator;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.main.pojo.Response;
import com.main.utils.CommonUtils;
import com.main.utils.Constant;

@Controller
@RequestMapping("/upload/**")
public class UploadController {

	private static final Logger logger = LoggerFactory.getLogger(UploadController.class);

	@RequestMapping(value = "/", method = RequestMethod.GET)
	public String upload(Model model, HttpServletRequest request) {
		if(request.getSession().getAttribute("uploader") == null){
			return "redirect:/uploader/login?ReturnUrl=upload";
		}
		return "upload";
	}

	@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
	public @ResponseBody
	Response uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) {
		Response result = new Response();
		Iterator<String> itr = request.getFileNames();
		MultipartFile mpf = null;

		while (itr.hasNext()) {

			mpf = request.getFile(itr.next());
			String fileType = mpf.getOriginalFilename().substring(mpf.getOriginalFilename().lastIndexOf("."));
			Date date = new Date();
			String randomFileName = String.valueOf(date.getTime()) + String.valueOf(Math.random()).replace(".", "")+ fileType;
			try {
				String path = request.getSession().getServletContext().getRealPath("/") + Constant.PHOTOS_PATH;
				String folderPath = path + "/" + CommonUtils.formatDate(date);
				File folder = new File(folderPath);
				if(!folder.exists()){
					folder.mkdir();
				}
				FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream( folderPath + "/" + randomFileName));
//				result.setData(request.getContextPath() + "/" + Constant.PHOTOS_PATH + "/" + folder.getName() + str);
				result.setData(folder.getName() + "/"+ randomFileName);

			} catch (IOException e) {
				result.setSuccess(false);
				result.setMsg(e.getMessage());
				e.printStackTrace();
			}
		}
		return result;
	}

}
